/**
 * 调解服务相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取调解案例列表
 * @param {object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.keyword - 搜索关键词
 * @param {number} params.status - 调解状态
 * @param {string} params.category - 调解类别
 * @returns {Promise} 调解案例列表
 */
export const getMediationList = (params = {}) => {
  return request.get('/mediation/list', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '', status, category } = queryParams
    
    // 模拟调解案例数据
    const mockMediations = Array.from({ length: 80 }, (_, index) => ({
      id: index + 1,
      caseNo: `MD${new Date().getFullYear()}${String(index + 1).padStart(6, '0')}`,
      title: `调解案例${index + 1}`,
      category: ['民事纠纷', '商事纠纷', '劳动争议', '消费纠纷', '物业纠纷'][Math.floor(Math.random() * 5)],
      status: Math.floor(Math.random() * 5) + 1, // 1-5
      statusName: ['待受理', '调解中', '调解成功', '调解失败', '已撤销'][Math.floor(Math.random() * 5)],
      applicantName: `申请人${index + 1}`,
      applicantPhone: `138${String(index + 1).padStart(8, '0')}`,
      respondentName: `被申请人${index + 1}`,
      respondentPhone: `139${String(index + 1).padStart(8, '0')}`,
      disputeAmount: Math.floor(Math.random() * 100000) / 100,
      description: `这是第${index + 1}个调解案例的描述信息`,
      mediatorName: `调解员${Math.floor(Math.random() * 10) + 1}`,
      applyTime: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString(),
      acceptTime: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000).toISOString() : null,
      completeTime: Math.random() > 0.5 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() : null,
      createTime: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredMediations = mockMediations
    if (keyword) {
      filteredMediations = mockMediations.filter(mediation => 
        mediation.caseNo.includes(keyword) || 
        mediation.title.includes(keyword) ||
        mediation.applicantName.includes(keyword) ||
        mediation.respondentName.includes(keyword)
      )
    }
    if (status) {
      filteredMediations = filteredMediations.filter(mediation => mediation.status === Number(status))
    }
    if (category) {
      filteredMediations = filteredMediations.filter(mediation => mediation.category === category)
    }
    
    // 分页
    const total = filteredMediations.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredMediations.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取调解案例详情
 * @param {number} id - 案例ID
 * @returns {Promise} 案例详情
 */
export const getMediationDetail = (id) => {
  return request.get(`/mediation/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      caseNo: `MD2024${String(id).padStart(6, '0')}`,
      title: `调解案例${id}`,
      category: '民事纠纷',
      status: 2,
      statusName: '调解中',
      // 申请人信息
      applicantName: `申请人${id}`,
      applicantPhone: `138${String(id).padStart(8, '0')}`,
      applicantIdCard: `110101199001010${String(id).padStart(3, '0')}`,
      applicantAddress: '北京市朝阳区测试街道123号',
      // 被申请人信息
      respondentName: `被申请人${id}`,
      respondentPhone: `139${String(id).padStart(8, '0')}`,
      respondentIdCard: `110101199001020${String(id).padStart(3, '0')}`,
      respondentAddress: '北京市海淀区测试路456号',
      // 纠纷信息
      disputeAmount: 5000.00,
      disputeReason: '合同纠纷',
      description: '这是一个关于合同履行的纠纷案例，双方对合同条款理解存在分歧。',
      evidence: [
        { name: '合同文件.pdf', url: '/files/contract.pdf', size: 1024000 },
        { name: '转账记录.jpg', url: '/files/transfer.jpg', size: 512000 }
      ],
      // 调解信息
      mediatorName: '张调解员',
      mediatorPhone: '13800000001',
      mediationPlace: '调解中心第一调解室',
      mediationTime: '2024-02-15T14:00:00.000Z',
      // 时间信息
      applyTime: '2024-01-15T10:00:00.000Z',
      acceptTime: '2024-01-16T09:00:00.000Z',
      completeTime: null,
      createTime: '2024-01-15T10:00:00.000Z',
      updateTime: new Date().toISOString(),
      // 调解记录
      records: [
        {
          id: 1,
          type: 'apply',
          title: '提交调解申请',
          content: '申请人提交调解申请',
          operatorName: `申请人${id}`,
          createTime: '2024-01-15T10:00:00.000Z'
        },
        {
          id: 2,
          type: 'accept',
          title: '受理申请',
          content: '调解中心受理申请，分配调解员',
          operatorName: '系统',
          createTime: '2024-01-16T09:00:00.000Z'
        },
        {
          id: 3,
          type: 'schedule',
          title: '安排调解',
          content: '安排调解时间和地点',
          operatorName: '张调解员',
          createTime: '2024-01-17T14:00:00.000Z'
        }
      ]
    })
  })
}

/**
 * 申请调解
 * @param {object} data - 申请数据
 * @returns {Promise} 申请结果
 */
export const applyMediation = (data) => {
  return request.post('/mediation/apply', data, {}, (params) => {
    const { 
      title, category, disputeAmount, description,
      applicantName, applicantPhone, applicantIdCard,
      respondentName, respondentPhone, respondentIdCard
    } = params
    
    if (!title || !category || !description || !applicantName || !applicantPhone || !respondentName || !respondentPhone) {
      return mockError('请填写完整的申请信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      caseNo: `MD${new Date().getFullYear()}${String(Date.now()).slice(-6)}`,
      status: 1,
      statusName: '待受理',
      ...params,
      applyTime: new Date().toISOString(),
      createTime: new Date().toISOString()
    }, '调解申请提交成功')
  })
}

/**
 * 更新调解申请
 * @param {number} id - 案例ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateMediation = (id, data) => {
  return request.put(`/mediation/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '调解信息更新成功')
  })
}

/**
 * 撤销调解申请
 * @param {number} id - 案例ID
 * @param {object} data - 撤销原因
 * @returns {Promise} 撤销结果
 */
export const cancelMediation = (id, data) => {
  return request.put(`/mediation/${id}/cancel`, data, {}, () => {
    return mockSuccess({
      id: Number(id),
      status: 5,
      statusName: '已撤销',
      cancelTime: new Date().toISOString()
    }, '调解申请撤销成功')
  })
}

/**
 * 获取调解记录
 * @param {number} id - 案例ID
 * @returns {Promise} 调解记录
 */
export const getMediationRecords = (id) => {
  return request.get(`/mediation/${id}/records`, {}, {}, () => {
    return mockSuccess([
      {
        id: 1,
        mediationId: Number(id),
        type: 'apply',
        title: '提交调解申请',
        content: '申请人提交调解申请，等待受理',
        operatorName: '申请人',
        operatorType: 'applicant',
        createTime: '2024-01-15T10:00:00.000Z'
      },
      {
        id: 2,
        mediationId: Number(id),
        type: 'accept',
        title: '受理申请',
        content: '调解中心受理申请，分配调解员张某',
        operatorName: '系统',
        operatorType: 'system',
        createTime: '2024-01-16T09:00:00.000Z'
      },
      {
        id: 3,
        mediationId: Number(id),
        type: 'contact',
        title: '联系当事人',
        content: '调解员联系双方当事人，了解基本情况',
        operatorName: '张调解员',
        operatorType: 'mediator',
        createTime: '2024-01-17T10:00:00.000Z'
      },
      {
        id: 4,
        mediationId: Number(id),
        type: 'schedule',
        title: '安排调解',
        content: '安排调解时间：2024年2月15日14:00，地点：调解中心第一调解室',
        operatorName: '张调解员',
        operatorType: 'mediator',
        createTime: '2024-01-17T14:00:00.000Z'
      },
      {
        id: 5,
        mediationId: Number(id),
        type: 'mediate',
        title: '开始调解',
        content: '双方当事人到场，开始正式调解',
        operatorName: '张调解员',
        operatorType: 'mediator',
        createTime: '2024-02-15T14:00:00.000Z'
      }
    ])
  })
}

/**
 * 添加调解记录
 * @param {number} id - 案例ID
 * @param {object} data - 记录数据
 * @returns {Promise} 添加结果
 */
export const addMediationRecord = (id, data) => {
  return request.post(`/mediation/${id}/records`, data, {}, (params) => {
    return mockSuccess({
      id: Date.now(),
      mediationId: Number(id),
      ...params,
      createTime: new Date().toISOString()
    }, '调解记录添加成功')
  })
}

/**
 * 获取调解员列表
 * @returns {Promise} 调解员列表
 */
export const getMediatorList = () => {
  return request.get('/mediation/mediators', {}, {}, () => {
    return mockSuccess(Array.from({ length: 20 }, (_, index) => ({
      id: index + 1,
      name: `调解员${index + 1}`,
      phone: `138${String(index + 1).padStart(8, '0')}`,
      email: `mediator${index + 1}@example.com`,
      specialties: ['民事纠纷', '商事纠纷', '劳动争议'].slice(0, Math.floor(Math.random() * 3) + 1),
      experience: Math.floor(Math.random() * 20) + 1,
      successRate: Math.floor(Math.random() * 30) + 70,
      caseCount: Math.floor(Math.random() * 500) + 50,
      status: Math.random() > 0.2 ? 1 : 0,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString()
    })))
  })
}

/**
 * 获取调解统计数据
 * @param {object} params - 查询参数
 * @returns {Promise} 统计数据
 */
export const getMediationStats = (params = {}) => {
  return request.get('/mediation/stats', params, {}, () => {
    return mockSuccess({
      total: 1250,
      pending: 45,
      processing: 78,
      success: 980,
      failed: 125,
      cancelled: 22,
      successRate: 78.4,
      avgDuration: 15.6, // 平均调解天数
      monthlyStats: Array.from({ length: 12 }, (_, index) => ({
        month: index + 1,
        total: Math.floor(Math.random() * 100) + 50,
        success: Math.floor(Math.random() * 80) + 40,
        failed: Math.floor(Math.random() * 20) + 5
      })),
      categoryStats: [
        { category: '民事纠纷', count: 450, percentage: 36 },
        { category: '商事纠纷', count: 320, percentage: 25.6 },
        { category: '劳动争议', count: 280, percentage: 22.4 },
        { category: '消费纠纷', count: 150, percentage: 12 },
        { category: '物业纠纷', count: 50, percentage: 4 }
      ]
    })
  })
}

/**
 * 上传调解证据
 * @param {number} id - 案例ID
 * @param {FormData} formData - 文件数据
 * @returns {Promise} 上传结果
 */
export const uploadMediationEvidence = (id, formData) => {
  return request.upload(`/mediation/${id}/evidence`, formData, {}, () => {
    return mockSuccess({
      id: Date.now(),
      mediationId: Number(id),
      filename: 'evidence.pdf',
      originalName: '证据文件.pdf',
      size: 1024000,
      url: '/files/evidence.pdf',
      uploadTime: new Date().toISOString()
    }, '证据上传成功')
  })
}

/**
 * 删除调解证据
 * @param {number} id - 案例ID
 * @param {number} evidenceId - 证据ID
 * @returns {Promise} 删除结果
 */
export const deleteMediationEvidence = (id, evidenceId) => {
  return request.delete(`/mediation/${id}/evidence/${evidenceId}`, {}, () => {
    return mockSuccess(null, '证据删除成功')
  })
}

/**
 * 获取调解协议模板
 * @returns {Promise} 协议模板
 */
export const getMediationTemplates = () => {
  return request.get('/mediation/templates', {}, {}, () => {
    return mockSuccess([
      {
        id: 1,
        name: '民事纠纷调解协议',
        category: '民事纠纷',
        content: '调解协议模板内容...',
        createTime: '2024-01-01T00:00:00.000Z'
      },
      {
        id: 2,
        name: '商事纠纷调解协议',
        category: '商事纠纷',
        content: '调解协议模板内容...',
        createTime: '2024-01-01T00:00:00.000Z'
      },
      {
        id: 3,
        name: '劳动争议调解协议',
        category: '劳动争议',
        content: '调解协议模板内容...',
        createTime: '2024-01-01T00:00:00.000Z'
      }
    ])
  })
}